<?php
/**
 * CreateTime: 2023/6/1 14:24
 */

namespace App\Console\Commands;


use App\Consts\BaseConsts\BaseConsts;
use App\Consts\MeLawCaseConsts\MeLawCaseListConsts;
use App\Consts\TableConsts\TableConsts;
use App\Func\CoverFunc;
use App\Models\MeClient\MeClientModel;
use App\Models\MeLawCase\MeLawCase;
use App\Models\MeLawCase\MeLawCaseLawLetterZZModel;
use App\Models\ShortLink\ShortLinkModel;
use App\Scopes\MediationStaffScope;
use App\Tools\DocxGenerator\FormatDocx;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Redis;
use setasign\Fpdi\Fpdi;


class MeLatterZhiZCommand  extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'sendLawZhiZhiMeLatter {--split-number=0}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command sendLawZhiZhiMeLatter ';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    private function getLetterNumbers($clientId){
        // 记录缓存的客户端和 code 数据
        $clientCodeList = Redis::get('mediation_client_code_list');
        if($clientCodeList === null){
            $clientModel = new MeClientModel();
            $clientCodeArray = array_column($clientModel->select(['client_id','client_code'])->get()->toArray(),'client_code','client_id');
            $clientCodeList = json_encode($clientCodeArray,256);
            Redis::set('mediation_client_code_list', $clientCodeList);
        }
        $clientCodeMap =  json_decode($clientCodeList,true);
        $code = $clientCodeMap[$clientId];
        // 这里需要一个定时任务清理器
        $count = Redis::get('law_letter_count_zz'.date("Y-m").$code);
        if($count === null){
            $lawCaseLetterModel = new MeLawCaseLawLetterZZModel();
            $count = $lawCaseLetterModel
                ->withoutGlobalScope(MediationStaffScope::class)
                ->where('client_id',$clientId)
                ->where('created_time','>=',date("Y-m-d",time()))
                ->count();
            Redis::set('law_letter_count_zz'.date("Y-m").$code, $count);
        }
        $number = $count + 1;
        return [
            'count' => $number,
            'code' => $code
        ];
    }

    private function createdWord($template_data_json_str,$clientTempFileName){
        // FpdiCLASS
        $pdf = new Fpdi();
        // 路径
        $appPath= storage_path("app");
        $appTempPath= storage_path("app/lawLatter");

        $path = storage_path('app/defaultTemplate/'.$clientTempFileName);
        dump($path);
        if(!is_file($path)){
            dump("文件不存在");
            return false;
        }
        // 根据客户名称和类型生成文件名
        $fileName = "law_letter_".time();
        $fileExt = "docx";
        $fileUrl = FormatDocx::formatClientEvaluationTemplateReplace(
            $template_data_json_str,
            $path,
            [
                "file_name"=> $fileName,
                "create_at"=> time(),
                "file_ext"=> $fileExt,
            ]
        );
        dump($fileUrl);
        /**
         * "oldPath" => "/node/docgen/law_letter_1686821831.pdf"
         * "newPath" => "templateFormat/20230615/law_letter_1686821831.pdf"
         */
        $path = FormatDocx::wordToPdf(
            $fileUrl,
            $fileName.".".$fileExt
        );
        dump($path);
        // 为当前PDF添加水印
        $pageCount = $pdf->setSourceFile($appPath.DIRECTORY_SEPARATOR.$path['newPath']);
        //遍历所有页面
        for ($pageNo = 1; $pageNo <= $pageCount; $pageNo++){
            //导入页面
            $templateId = $pdf->importPage($pageNo);
            //获取导入页面的大小
            $size = $pdf->getTemplateSize($templateId);
            //创建页面（横向或纵向取决于导入的页面大小）
            if ($size['width'] > $size['height']){
                $pdf->AddPage('L', array($size['width'], $size['height']));
            }else {
                $pdf->AddPage('P', array($size['width'], $size['height']));
            }
            //使用导入的页面
            $pdf->useTemplate($templateId);
            if(false){//文字水印
                //设置字体
                //$pdf->SetFont('Arial','B','24');
                $family = ['courier', 'helvetica', 'times', 'symbol', 'zapfdingbats'];
                $pdf->SetFont('helvetica','U','50');
                //设置位置 - 加在中间位置
                $center_x = $size['width']/2;
                $center_y = $size['height']/2;
                $pdf->SetXY($center_x, $center_y);
                //写入水印 - 中文会乱码 建议使用中文图片
                $pdf->Write(7, 'ROOT_ICO');
            }else{//图片水印
                $center_x = $size['width']/2 - 40;$center_y = $size['height']/2;
                $pdf->image(__DIR__."/defaultWatermarkChaoYueLaw.png", 0, 0,210);//全屏背景水印
            }
        }

        // 输出pdf
        // I输出output，D下载download，F保存file_put_contents，S返回return
        $pdfWaterName = basename($path['newPath']);
        $pdfWaterArray = explode('.',$pdfWaterName);
        $pdfReqName = $pdfWaterArray[0].'_watermark.'.$pdfWaterArray[1];
        $waterPdfPath = str_replace($pdfWaterName, $pdfReqName, $path['newPath']);
        // 水印完整路径
        $waterPdfPathExt = $appPath.DIRECTORY_SEPARATOR.$waterPdfPath;
        $pdfContent = $pdf->Output('S');
        $flag = file_put_contents($waterPdfPathExt, $pdfContent);
        if(!is_dir($appTempPath)){
            mkdir($appTempPath);
        }
        if(!is_dir($appTempPath.DIRECTORY_SEPARATOR.date("Ymd"))){
            mkdir($appTempPath.DIRECTORY_SEPARATOR.date("Ymd"));
        }
        // 计算文件唯一hash值

        $hash = hash_file('sha256',$waterPdfPathExt);
        $pdfToImageInfo = CoverFunc::coverPdfToPng($waterPdfPathExt,$appTempPath.DIRECTORY_SEPARATOR.date("Ymd"));

        return [
            'pdf_path' => $path['newPath'],
            'pdf_water_path' => $waterPdfPath,
            'pdf_hash' => $hash,
            'image_group' => str_replace($appPath.DIRECTORY_SEPARATOR,'',$pdfToImageInfo['image_output_path'])
        ];
    }

    private function  setDefaultFiledByClient($clientId,$data){
        $codeInfo = $this->getLetterNumbers($clientId);
        switch ($clientId){
            case 16:
                $time = time();
                $data['now_year'] = date("Y",$time);
                $data['now_month'] = str_pad(date("m"), 2, '0', STR_PAD_LEFT);
                $data['now_day'] = str_pad(date("d",$time), 2, '0', STR_PAD_LEFT);
                if($codeInfo['count']<999){
                    $data['nums'] = "CY-".$codeInfo['code']."-".$data['now_month']."-2-".str_pad($codeInfo['count'], 4, '0', STR_PAD_LEFT);;
                }else{
                    $data['nums'] = "CY-".$codeInfo['code']."-".$data['now_month']."-2-".$codeInfo['count'];
                }
                return $data;
            case 17:
                $time = time();
                $data['now_month'] = str_pad(date("m"), 2, '0', STR_PAD_LEFT);
                $data['end_time'] = date("Y年m月d日",$time);
                if($codeInfo['count']<999){
                    $data['nums'] = "CY-".$codeInfo['code']."-".$data['now_month']."-2-".str_pad($codeInfo['count'], 4, '0', STR_PAD_LEFT);
                }else{
                    $data['nums'] = "CY-".$codeInfo['code']."-".$data['now_month']."-2-".$codeInfo['count'];
                }
                $data['make_date'] = $data['end_time'];
                return $data;
            case 20:
                $time = time();
                $data['account_name_simp'] =  str_replace(["股份","有限","公司","中国"],["","","",""],$data['account_name']);
                $data['now_month'] = str_pad(date("m"), 2, '0', STR_PAD_LEFT);
                $data['end_time'] = date("Y年m月d日",$time);
                if($codeInfo['count']<999){
                    $data['nums'] = "CY-".$codeInfo['code']."-".$data['now_month']."-2-".str_pad($codeInfo['count'], 4, '0', STR_PAD_LEFT);
                }else{
                    $data['nums'] = "CY-".$codeInfo['code']."-".$data['now_month']."-2-".$codeInfo['count'];
                }
                $data['make_date'] = $data['end_time'];
                return $data;
            default:
                $time = time();
                $data['now_month'] = str_pad(date("m"), 2, '0', STR_PAD_LEFT);
                $data['end_time'] = date("Y年m月d日",$time);
                if($codeInfo['count']<999){
                    // 2 纸质档
                    $data['nums'] = "CY-".$codeInfo['code']."-".$data['now_month']."-2-".str_pad($codeInfo['count'], 4, '0', STR_PAD_LEFT);
                }else{
                    $data['nums'] = "CY-".$codeInfo['code']."-".$data['now_month']."-2-".$codeInfo['count'];
                }
                $data['make_date'] = date("Y年m月d日",$time);
                return $data;
        }
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        // 案件m 调解函m 短链接m
        $lawCaseModel = new MeLawCase();
        $shortLinkModel = new ShortLinkModel();
        $meLawCaseLawLetter = new MeLawCaseLawLetterZZModel();
        $key = MeLawCaseListConsts::LAW_LATTER_R_LIST_ZZ_KEY;
        // ID自增用作唯一值
        $count = 0;
        $keyNumber = intval(strtolower($this->option('split-number')));
        echo "命令启动";
        while(true){
            try {
                app()->gcHelper->gfGetRedis()->list($key.".".$keyNumber)->for_each(function ($v,$list_length) use ($lawCaseModel,$shortLinkModel,$meLawCaseLawLetter,&$count) {
                    // 获取自定义字段 过滤已经生成过律师函的
                    echo "弹出队列\n";
                    $req = $lawCaseModel->select(
                        [
                            'law_case.*',
                            'client.client_id',
                            'client.client_name',
                            'file.file_name as client_temp_law_filename',
                            'client.client_code',
                            'law_case_phone.phone_number'
                        ]
                    )
                        ->leftjoin(TableConsts::ME_CLIENT." as client",'client.client_id','law_case.client_id')
                        ->leftjoin(TableConsts::CY_FILE_TABLE_NAME." as file",'client.client_temp_law_not_sign_file_id','file.file_id')
                        ->leftjoin(TableConsts::ME_LAW_CASE_PHONE." as law_case_phone",'law_case_phone.law_case_phone_id','law_case.main_respondent_phone_id')
                        ->withoutGlobalScope(MediationStaffScope::class)
                        ->where('law_case.law_case_id',(int)$v)
                        ->where('law_case.status',BaseConsts::STATUS_NORMAL)
                        ->where('law_case.is_send_law_latter',2)
                        ->first();
                    if($req){
                        echo "处理数据中\n";
                        $templateArray = $req->toArray();
                        $lawCaseCustomArray = json_decode($templateArray['law_case_custom'],true);
                        // 解开自定义字段并且合并数组
                        unset($templateArray['law_case_custom']);
                        if(!$lawCaseCustomArray){
                            $lawCaseCustomArray = [];
                        }
                        $templateDisposeArray = array_merge($templateArray,$lawCaseCustomArray);
                        // 通过客户ID和数组设置默认字段
                        $templateDisposeArray = $this->setDefaultFiledByClient($req['client_id'],$templateDisposeArray);
                        // 生成文件
                        $imgInfo = $this->createdWord(json_encode($templateDisposeArray,256),$req['client_temp_law_filename']);
                        // 不存在模板则自动跳过
                        if($imgInfo){
                            echo "进入模板生成\n";
                            echo "新增编号序列\n";
                            $lawCaseModel->updateData([
                                'law_case_id' => (int)$v,
                                'is_send_zz_law_letter' => 1
                            ],true);
                            // 插入纸质函Model
                            // 添加调解函库
                            $addLawLatterReq = $meLawCaseLawLetter->add([
                                'law_case_id' => (int)$v,
                                'client_id' => $req['client_id'],
                                'latter_nums' =>  $templateDisposeArray['nums'],
                                'law_case_id_card' => $templateArray['respondent_id_card'],
                                'pdf_water_path' => $imgInfo['pdf_water_path'],
                                'pdf_path' => $imgInfo['pdf_path'],
                                'pdf_path_hash' => $imgInfo['pdf_hash'],
                                'file_image_dir' => $imgInfo['image_group']
                            ],true);
                            if($addLawLatterReq){
                                // 递增缓存当日count值
                                Redis::incr('law_letter_count_zz'.date("Y-m").$req['client_code']);
                            }
                        }
                    }
                });

                // 没有队列自动休息一秒
                sleep(1);
            }catch (\Exception $exception){
                dump("异常");
                dump($exception);
                dd($exception->getMessage().$exception->getFile().$exception->getLine());
            }
        }
    }
}
